import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mmkv/mmkv.dart';
import 'package:seedfour/app/routes/Event.dart';
import 'package:seedfour/app/services/common_service.dart';

import '../../../constants.dart';
import '../../../models/notice_v2_list_entity.dart';
import '../../../models/raw_data.dart';
import '../../../remote/request.dart';
import '../../../routes/app_routes.dart';
import '../../../services/api_service.dart';
import '../../module_notice/notice_edit/logic.dart';
import '../../module_seal/seal_create/logic.dart';
import '../../web_screen/screen_params.dart';
import 'state.dart';

class HomeLogic extends GetxController with GetSingleTickerProviderStateMixin {
  final HomeState state = HomeState();
  final apiService = Get.put(ApiService());
  final commonService = Get.put(CommonService());

  late TabController tabController;
  late ScrollController scrollController;

  var currentPaperType = SealPaperType.all.obs;
  var createPaperType = Rxn<SealPaperType>();

  final mmkv = MMKV.defaultMMKV();

  @override
  void onInit() {
    super.onInit();
    tabController =
        TabController(length: state.statisticsTitles.length, vsync: this);
    tabController.addListener(() {});

    scrollController = ScrollController();
    scrollController.addListener(() {
      if (scrollController.position.pixels >=
          scrollController.position.maxScrollExtent) {
        _getRecommendCaseList(state.page);
      }
    });

    eventBus.on<ChangeAccountEvent>().listen((event) {
      printInfo(info: '------------------------------------------ 监听事件');
      reload();
    });

    reload();
  }

  void reload() {
    state.page = 1;
    state.noticeList.clear();
    state.isLoading.value = true;

    _getRecommendCaseList(state.page);
    _getMessageAlert();
    _getTitle();
  }

  void onSelectedCreateType(SealPaperType type) {
    createPaperType.value = type;
  }

  void toCreateSealApply() async {
    dynamic result;
    result = await Get.toNamed(RouteGet.sealCreate,
        arguments: SealCreateParams(sealPaperType: createPaperType.value!));
    if (result != null && result as bool == true) {
      reload();
    }
  }

  void _getTitle() {
    state.title.value = commonService.getUser().targetSite!.name;
    state.iconUrl.value = commonService.getUser().targetSite!.logo;
  }

  void _getRecommendCaseList(int page) {
    apiService
        .getNoticeRecommendList(
            page, state.pageSize, commonService.getRole(), 'pub')
        .then((value) => {
              state.isLoading.value = false,
              state.page++,
              if (value != null)
                {
                  state.noticeList.addAll(value.data ?? []),
                  if (value.data?.length != state.pageSize)
                    {state.bottomTips.value = state.noMoreTip}
                  else
                    {state.bottomTips.value = state.loadingTip}
                }
              else
                {state.bottomTips.value = state.noMoreTip}
            });
  }

  void _getMessageAlert() {
    apiService.getMessageAlert(commonService.getRole()).then((value) => {
          if (value != null) {state.messageCount.value = value.messageCnt ?? 0}
        });
  }

  void onSelectPrintType(int index) {
    state.selectedPrintIndex.value = index;
  }

  void onCancelSelectPrintType() {
    state.selectedPrintIndex.value = 0;
  }

  /// 点击顶部导航快捷按钮
  void clickNavigationButton(String businessType) {
    _getH5Url(businessType);
  }

  // 创建案源
  void toCreateNotice() async {
    dynamic result = await Get.toNamed(RouteGet.noticeEdit,
        arguments: NoticeEditParams(isCreate: true));

    if (result != null && result == true) {
      reload();
    }
  }

  // 点击消息列表图标
  void toMessageList() {
    state.hasNewMessage.value = false;
    Get.toNamed(RouteGet.messageList, arguments: state.messageCount.value)
        ?.then((value) => _getMessageAlert());
  }

  void toNoticeList() {
    Get.toNamed(RouteGet.noticeList)
        ?.then((value) => {_refreshNoticeReadStatus()});
  }

  // 查看案源详情
  void toNoticeDetail(NoticeV2Data item) {
    Get.toNamed(RouteGet.noticeDetail, arguments: item.id);
  }

  void toAIPage() {
    String? token = commonService.getToken();
    String orgId = commonService.getUser().targetSite!.owner;
    String url =
        'https://www.seedfour.com/clicms/#/shifu-ai?orgId=$orgId&token=$token';
    Get.toNamed(RouteGet.webScreen, arguments: WebScreenParams(url: url));
  }

  void _getH5Url(String businessType) => request(() async {
        String? token = commonService.getToken();

        RawData? result = await apiService.getBusinessUrl(token!, businessType);
        if (result != null) {
          if (result.value['code'] != 200) {
            Get.snackbar('提示', result.value['msg']);
            return;
          }
          Get.toNamed(RouteGet.webScreen,
              arguments: WebScreenParams(
                url: result.value['url'],
                businessType: businessType,
              ));
        }
      });

  void _refreshNoticeReadStatus() {
    state.hasNewNotice.value = false;
    for (int i = 0; i < state.noticeList.length; i++) {
      if (!mmkv.decodeBool('$kKeyNoticeReadTag${state.noticeList[i].id}')) {
        state.hasNewNotice.value = true;
        return;
      }
    }
  }

  @override
  void onClose() {
    tabController.dispose();
    super.onClose();
  }
}
